package com.icoolkj.mall.account.service.impl;

import com.icoolkj.mall.account.mapper.AccountMapper;
import com.icoolkj.mall.account.service.AccountService;
import com.icoolkj.mall.common.Result;
import com.icoolkj.mall.common.exception.BusinessException;
import io.seata.core.context.RootContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

/**
 * @author icoolkj
 * @version 1.0
 * @description
 * @createDate 2025/01/16 17:16
 */
@Service
public class AccountServiceImpl implements AccountService {

    Logger logger = LoggerFactory.getLogger(AccountServiceImpl.class);

    @Autowired
    private AccountMapper accountMapper;

    @Override
    @Transactional
    public void reduceBalance(Long userId, BigDecimal orderCost) {

        logger.info("[reduceBalance] currenet XID: {}", RootContext.getXID());

        checkBalance(userId, orderCost);

        int updateCount = accountMapper.reduceBalance(userId, orderCost, new Date());
        if(updateCount ==0 ){
            throw new BusinessException("reduce balance failed.");
        }
    }

    private void checkBalance(Long userId, BigDecimal orderCost) {
        BigDecimal balance = accountMapper.getBalance(userId);
        if(balance.compareTo(orderCost) < 0){
            throw new BusinessException("no enough balance.");
        }
    }

    @Override
    public Result<?> getBalanceAccount(Long userId) {
        BigDecimal balance = accountMapper.getBalance(userId);
        if(balance == null){
            return Result.fail("userId wrong, please check the userId");
        }
        return Result.ok(balance);
    }
}
